package com.gowants.pems.util;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import javax.annotation.PostConstruct;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.gowants.pems.mapper.SysLogMapper;
import com.gowants.pems.model.SysLog;

/**
 * @Author: 
 * @Date: 
 * @Description: 简单的内存缓存工具类
 */
@Component
public class Cache {
	
	
	    @Autowired
	    private SysLogMapper logMapper;

	    private static SysLogMapper service;

	    public @PostConstruct void init(){
        service= logMapper;
	    }

	
    /**
     * 键值对集合
     */
    private final static Map<String, Entity> map = new HashMap<>();
    /**
     * 定时器线程池，用于清除过期缓存
     */
    private final static ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();

    /**
     * 添加缓存
     *
     * @param key  键
     * @param data 值
     */
    public synchronized static void put(String key, Object data) {
        Cache.put(key, data, 0);
    }

    /**
     * 添加缓存
     *
     * @param key    键
     * @param data   值
     * @param expire 过期时间，单位：毫秒， 0表示无限长
     */
    public synchronized static void put(String key, Object data, long expire) {
    	 
    	try
    	{
    	
    	//清除原键值对
        Cache.remove(key);
        //设置过期时间
        if (expire > 0) {
            Future future = executor.schedule(new Runnable() {
                @Override
                public void run() {
                    //过期后清除该键值对
                    synchronized (Cache.class) {
                        map.remove(key);
                    }
                }
            }, expire, TimeUnit.MILLISECONDS);
            Entity entity=new Entity();
			entity.setkey(key);
			entity.setvalue(data);
			entity.setfuture(future);
            map.put(key, entity);
        } else {
            //不设置过期时间
        	 Entity entity=new Entity();
 			entity.setkey(key);
 			entity.setvalue(data);
            map.put(key, entity);
        }
    	}
    	catch(Exception e)
    	{
    		SysLog record = new SysLog();
    		 record.setCreateTime(DateUtil.getDate());
    	     record.setRemarks(e.getMessage());
    	     record.setType(3);
    	     record.setImportance(2);
    	     record.setId(UUID.randomUUID().toString());
    	     record.setName("缓存信息存入时错误,key:"+key+", data:"+data);
    	     service.save(record);
    	}
    }

    /**
     * 读取缓存
     *
     * @param key 键
     * @return
     */
    public synchronized static <T> T get(String key) {
        Entity entity = map.get(key);
        return entity == null ? null : (T) entity.value;
    }
    
    public synchronized static List<Entity> getList() {
    	 List <Entity> list = new ArrayList();
    	 
    	 Set<String> keySet = new HashSet<String>();
    	 keySet.addAll(map.keySet());
    	 List<String> keyList = new ArrayList<String>();
 		 keyList.addAll(keySet);
 		 for(String key : keyList)
 		 {
 			Entity entity=new Entity();
 			entity.setkey(key);
 			entity.setvalue(map.get(key).getvalue());
 			list.add(entity);
 		 }
        return list ;
    }
    
    

    /**
     * 清除缓存
     *
     * @param key 键
     * @return
     */
    public synchronized static <T> T remove(String key) {
        //清除原缓存数据
        Entity entity = map.remove(key);
        if (entity == null) {
            return null;
        }
        //清除原键值对定时器
        if (entity.future != null) {
            entity.future.cancel(true);
        }
        return (T) entity.value;
    }

    /**
     * 查询当前缓存的键值对数量
     *
     * @return
     */
    public synchronized static int size() {
        return map.size();
    }

  
}

